<?php

namespace app\api\controller;

use app\api\validation\Address;
use app\api\validation\ShoppingCart;
use app\services\ShoppingCartService;
use support\Request;

class ShoppingCartController
{
    public function list(Request $request)
    {
        try {
            $data = ShoppingCartService::list();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function add(Request $request)
    {
        $validate = new ShoppingCart();

        $data = $request->post();

        try {
            if (! $validate->check($request->post())) {
                throw new \Exception($validate->getError());
            }

            ShoppingCartService::add($data);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function reduce(Request $request)
    {
        $cartItemId = $request->post('cart_item_id');

        try {
            $result = ShoppingCartService::reduce(['id' => $cartItemId]);

            if (is_array($result)) {
                return err_rsp('库存不足', 400, ['stock' => $result[1]]);
            }

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function incr(Request $request)
    {
        $cartItemId = $request->post('cart_item_id');

        try {
            $result = ShoppingCartService::incr(['id' => $cartItemId]);

            if (is_array($result)) {
                return err_rsp('库存不足', 400, ['stock' => $result[1]]);
            }
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function setCount(Request $request)
    {
        $cartItemId = $request->post('cart_item_id');
        $count = $request->post('count', 1);

        try {
            $result = ShoppingCartService::setCount(['id' => $cartItemId, 'count' => $count]);

            if (is_array($result)) {
                return err_rsp('库存不足', 400, ['stock' => $result[1]]);
            }

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function delete(Request $request)
    {
        $cartItemIds = $request->post('cart_item_ids');

        try {
            ShoppingCartService::delete(['ids' => explode(',', $cartItemIds)]);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
}